package com.example.bluetooth_test;

import android.app.ActionBar;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class BluetoothActivity extends Activity {

	private static final String TAG = "BluetoothActivity";
	private String mConnectedDeviceName = null;
	// private ArrayAdapter<String> mConversationArrayAdapter;
	private BluetoothAdapter mBluetoothAdapter = null;
	private BluetoothService mBluetoothService = null;

	public static final int MESSAGE_STATE_CHANGE = 1;
	public static final int MESSAGE_READ = 2;
	public static final int MESSAGE_WRITE = 3;
	public static final int MESSAGE_DEVICE_NAME = 4;
	public static final int MESSAGE_TOAST = 5;

	public static final String DEVICE_NAME = "device_name";
	public static final String TOAST = "toast";

	private static final int REQUEST_CONNECT_DEVICE_INSECURE = 1;
	private static final int REQUEST_ENABLE_BT = 2;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bluetooth);
		Log.e(TAG, "== onCreate() ==");
		
		Button leftButton = (Button) findViewById(R.id.button1);
		Button BreakButton = (Button) findViewById(R.id.button2);
		Button RightButton = (Button) findViewById(R.id.button3);
		
		leftButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
			String ab = "a";
			byte[] send = ab.getBytes();
			mBluetoothService.write(send);	
			}
		});

		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		if (mBluetoothAdapter == null) {
			Toast.makeText(this, "Bluetooth is not available",
					Toast.LENGTH_LONG).show();
			finish();
			return;
		}

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.e(TAG, "== onStart() ==");
		if (!mBluetoothAdapter.isEnabled()) {
			Intent enableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
		} else {
			mBluetoothService = new BluetoothService(this);
			// mConversationArrayAdapter = new ArrayAdapter<String>(this,
			// R.layout.activity_message);
		}

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.e(TAG, "== onDestroy() ==");
		if (mBluetoothService != null)
			mBluetoothService.stop();
	}

	private void ensureDiscoverable() {
		// TODO Auto-generated method stub
		Log.e(TAG, "** ensureDiscoverable() **");
		if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
			Intent discoverableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			discoverableIntent.putExtra(
					BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
			startActivity(discoverableIntent);

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		Log.e(TAG, "onActivityResult " + requestCode);

		switch (requestCode) {
		case REQUEST_CONNECT_DEVICE_INSECURE:
			if (resultCode == Activity.RESULT_OK) {
				connectDevice(data, false);
			}
			break;
		case REQUEST_ENABLE_BT:
			// When the request to enable Bluetooth returns
			if (resultCode == Activity.RESULT_OK) {
				// Bluetooth is now enabled, so set up a chat session
			} else {
				// User did not enable Bluetooth or an error occurred
				Log.d(TAG, "BT not enabled");
				Toast.makeText(this, R.string.bt_not_enabled_leaving,
						Toast.LENGTH_SHORT).show();
				finish();
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private void connectDevice(Intent data, boolean secure) {
		// Get the device MAC address
		String address = data.getExtras().getString(
				DeviceListActivity.EXTRA_DEVICE_ADDRESS);
		// Get the BluetoothDevice object
		BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
		// Attempt to connect to the device
		mBluetoothService.connect(device, secure);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_bluetooth, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		// return super.onOptionsItemSelected(item);
		Intent serverIntent = null;
		switch (item.getItemId()) {
		case R.id.insecure_connect_scan:
			serverIntent = new Intent(this, DeviceListActivity.class);
			startActivityForResult(serverIntent,
					REQUEST_CONNECT_DEVICE_INSECURE);
			return true;
		case R.id.discoverable:
			ensureDiscoverable();
			return true;
		}
		return false;
	}

	private final void setStatus(int resId) {
		final ActionBar actionBar = getActionBar();
		actionBar.setSubtitle(resId);
	}

	private final void setStatus(CharSequence subTitle) {
		final ActionBar actionBar = getActionBar();
		actionBar.setSubtitle(subTitle);
	}

	// private final Handler mHandler = new Handler() {
	// @Override
	// public void handleMessage(Message msg) {
	// switch (msg.what) {
	// case MESSAGE_STATE_CHANGE:
	// Log.e(TAG, "--MESSAGE_STATE_CHANGE: " + msg.arg1);
	// switch (msg.arg1) {
	// case BluetoothService.STATE_CONNECTED:
	// setStatus(getString(R.string.title_connected_to,
	// mConnectedDeviceName));
	// mConversationArrayAdapter.clear();
	// break;
	// case BluetoothService.STATE_CONNECTING:
	// setStatus(R.string.title_connecting);
	// break;
	// case BluetoothService.STATE_LISTEN:
	// case BluetoothService.STATE_NONE:
	// setStatus(R.string.title_not_connected);
	// break;
	// }
	// break;
	// case MESSAGE_WRITE:
	// byte[] writeBuf = (byte[]) msg.obj;
	// // construct a string from the buffer
	// String writeMessage = new String(writeBuf);
	// mConversationArrayAdapter.add("Me:  " + writeMessage);
	// break;
	// }
	// }
	// };
}
